// routes/answerRoutes.js
const express = require('express');
const router = express.Router();
const pool = require('./db');

// 提交选择题答案
router.post('/submit-choice-answer', async (req, res) => {
    const { practiceId, questionOrder, userId, userAnswer } = req.body;
    
    try {
        // 1. 从choice_questions表获取正确答案和分值
        const [choiceQuestions] = await pool.execute(
            'SELECT correct_answer, score FROM choice_questions WHERE practice_id = ? AND question_order = ?',
            [practiceId, questionOrder]
        );
        
        if (choiceQuestions.length === 0) {
            return res.status(404).json({ success: false, message: '题目不存在' });
        }
        
        const { correct_answer, score } = choiceQuestions[0];
        
        // 2. 判断用户答案是否正确
        const isCorrect = userAnswer === correct_answer;
        const userScore = isCorrect ? score : 0;
        
        // 3. 检查用户是否已提交过该题目
        const [commitedQuestions] = await pool.execute(
            'SELECT practice_id FROM commited_choice_question WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
            [practiceId, userId, questionOrder]
        );
        
        if (commitedQuestions.length > 0) {
            // 4. 如果已提交，更新答案和分数
            await pool.execute(
                'UPDATE commited_choice_question SET commited_answer = ?, score = ? WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
                [userAnswer, userScore, practiceId, userId, questionOrder]
            );
        } else {
            // 5. 如果未提交，插入新记录
            await pool.execute(
                'INSERT INTO commited_choice_question (practice_id,commit_user_id,question_order,commited_answer,score) VALUES (?, ?, ?, ?, ?)',
                [practiceId, userId, questionOrder, userAnswer, userScore]
            );
        }
        
        res.json({ success: true, score: userScore });
    } catch (error) {
        console.error('提交选择题答案失败:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 提交填空题答案
router.post('/submit-fill-answer', async (req, res) => {
    const { practiceId, questionOrder, userId, answers } = req.body;
    
    try {
        // 1. 从fill_questions表获取正确答案和分值配置
        const [fillQuestions] = await pool.execute(
            'SELECT * FROM fill_questions WHERE practice_id = ? AND question_order = ?',
            [practiceId, questionOrder]
        );
        
        if (fillQuestions.length === 0) {
            return res.status(404).json({ success: false, message: '题目不存在' });
        }
        
        const question = fillQuestions[0];
        const correctAnswers = [
            question.blank1_answer,
            question.blank2_answer,
            question.blank3_answer,
        ];
        
        const scores = [
            question.blank1_score || 0,
            question.blank2_score || 0,
            question.blank3_score || 0
        ];
        
        // 2. 计算用户得分
        let userScore = 0;
        const userAnswers = [...answers]; // 复制用户答案数组
        
        // 填充null到固定长度（3个空）
        while (userAnswers.length < 3) {
            userAnswers.push(null);
        }
        
        for (let i = 0; i < 3; i++) {
            if (userAnswers[i] === correctAnswers[i]) {
                userScore += scores[i];
            }
        }
        
        // 3. 检查用户是否已提交过该题目
        const [commitedQuestions] = await pool.execute(
            'SELECT practice_id FROM commited_fill_question WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
            [practiceId, userId, questionOrder]
        );
        
        if (commitedQuestions.length > 0) {
            // 4. 如果已提交，更新答案和分数
            await pool.execute(
                `UPDATE commited_fill_question 
                 SET commited_answer1 = ?, commited_answer2 = ?, commited_answer3 = ?, score = ?
                 WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?`,
                [
                    userAnswers[0], userAnswers[1], userAnswers[2], userScore,
                    practiceId, userId, questionOrder
                ]
            );
        } else {
            // 5. 如果未提交，插入新记录
            await pool.execute(
                `INSERT INTO commited_fill_question 
                 (practice_id,commit_user_id, question_order, 
                  commited_answer1, commited_answer2, commited_answer3,score)
                 VALUES (?, ?, ?, ?, ?, ?, ?)`,
                [
                    practiceId, userId, questionOrder,
                    userAnswers[0], userAnswers[1], userAnswers[2],userScore
                ]
            );
        }
        
        res.json({ success: true, score: userScore });
    } catch (error) {
        console.error('提交填空题答案失败:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

// 提交解答题答案
router.post('/submit-essay-answer', async (req, res) => {    
    const { practiceId, questionOrder, userId, answer } = req.body;        
    try {        
        // 1. 检查题目是否存在        
        const [essayQuestions] = await pool.execute(            
        'SELECT * FROM essay_questions WHERE practice_id = ? AND question_order = ?',
                [practiceId, questionOrder]
        );                
        if (essayQuestions.length === 0) {            
            return res.status(404).json({ success: false, message: '题目不存在' });
        }                
        // 2. 检查用户是否已提交过该题目        
        const [commitedQuestions] = await pool.execute(            
        'SELECT practice_id FROM commited_essay_question WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
                [practiceId, userId, questionOrder]
        );                
        if (commitedQuestions.length > 0) {            
        // 3. 如果已提交，更新答案（score保持为null）            
            await pool.execute(                
            'UPDATE commited_essay_question SET commited_answer = ?, score = NULL WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
                    [answer, practiceId, userId, questionOrder]
            );
        } else {            
        // 4. 如果未提交，插入新记录（score置为null）            
        await pool.execute(                
        'INSERT INTO commited_essay_question (practice_id, commit_user_id, question_order, commited_answer, score) VALUES (?, ?, ?, ?, NULL)',
                    [practiceId, userId, questionOrder, answer]
                );
        }                
        res.json({ success: true, message: '解答题提交成功，等待教师评判' });
        } catch (error) {        
            console.error('提交解答题答案失败:', error);        
            res.status(500).json({ success: false, message: '服务器内部错误' });
        }
});

// 提交练习的接口
router.post('/submit-practice', async (req, res) => {    
const { practice_id, user_id } = req.body;
    try {        
        // 检查练习是否存在        
        const [practiceRows] = await pool.execute('SELECT * FROM practice WHERE practice_id = ?', [practice_id]);        
        if (practiceRows.length === 0) {            
            return res.status(404).json({ message: '练习不存在，不允许提交' });
        }
    const practice = practiceRows[0];
    // 检查是否已有提交记录        
    const [commitRows] = await pool.execute('SELECT * FROM commited_practice WHERE practice_id = ? AND commit_user_id = ?', [practice_id, user_id]);
    if (commitRows.length === 0) {            
    // 若不存在提交记录，插入新记录            
            const remaining_submit_times = practice.submit_times - 1;            
            await pool.execute('INSERT INTO commited_practice (practice_id,commit_user_id, remaining_submit_times) VALUES (?, ?, ?)', [practice_id, user_id, remaining_submit_times]);            
            return res.status(200).json({ message: '提交成功', remaining_submit_times });
        }
    const commit = commitRows[0];        
    if (commit.remaining_submit_times === 0) {            
            return res.status(403).json({ message: '剩余提交次数为 0，不允许提交' });
        }
        // 更新提交记录，减少剩余提交次数        
    const newRemainingTimes = commit.remaining_submit_times - 1;        
    await pool.execute('UPDATE commited_practice SET remaining_submit_times = ? WHERE practice_id = ? AND commit_user_id = ?', [newRemainingTimes, practice_id, user_id]);        
    return res.status(200).json({ message: '提交成功', remaining_submit_times: newRemainingTimes });
    }  catch (error) {        
        console.error('提交练习时出错:', error);        
        return res.status(500).json({ message: '服务器内部错误' });
    }
});

// 检查学生是否有该练习的提交记录
router.get('/check-submission', async (req, res) => {
    const { userId, practiceId } = req.query;
    try {
        const [commitRows] = await pool.execute('SELECT * FROM commited_practice WHERE practice_id = ? AND commit_user_id = ?', [practiceId, userId]);
        res.json({ hasSubmission: commitRows.length > 0 });
    } catch (error) {
        console.error('检查提交记录时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 统计学生提交的该练习的总分值
router.get('/calculate-total-score', async (req, res) => {
    const { userId, practiceId } = req.query;
    try {
        let totalScore = 0;

        // 统计选择题得分
        const [commitedChoiceQuestions] = await pool.execute('SELECT score FROM commited_choice_question WHERE practice_id = ? AND commit_user_id = ?', [practiceId, userId]);
        commitedChoiceQuestions.forEach(question => {
            totalScore += question.score || 0;
        });

        // 统计填空题得分
        const [commitedFillQuestions] = await pool.execute('SELECT score FROM commited_fill_question WHERE practice_id = ? AND commit_user_id = ?', [practiceId, userId]);
        commitedFillQuestions.forEach(question => {
            totalScore += question.score || 0;
        });

        // 统计解答题得分，未评判视为0
        const [commitedEssayQuestions] = await pool.execute('SELECT score FROM commited_essay_question WHERE practice_id = ? AND commit_user_id = ?', [practiceId, userId]);
        commitedEssayQuestions.forEach(question => {
            totalScore += question.score || 0;
        });

        res.json({ totalScore });
    } catch (error) {
        console.error('统计总分值时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 检查学生提交的练习是否被教师评判
router.get('/check-judgment', async (req, res) => {
    const { userId, practiceId } = req.query;
    try {
        const [commitedEssayQuestions] = await pool.execute('SELECT score FROM commited_essay_question WHERE practice_id = ? AND commit_user_id = ?', [practiceId, userId]);
        const isJudged = commitedEssayQuestions.every(question => question.score!== null);
        res.json({ isJudged });
    } catch (error) {
        console.error('检查评阅状态时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 获取选择题作答情况
router.get('/api/choice-questions/:practiceId', async (req, res) => {
    const { practiceId } = req.params;
    const { userId } = req.query;
    
    try {
        // 查询选择题信息
        const [questions] = await pool.execute(
            'SELECT q.*, cq.commited_answer as user_answer, cq.score as user_score ' +    
            'FROM choice_questions q ' +    
            'LEFT JOIN commited_choice_question cq ON q.question_order = cq.question_order AND cq.commit_user_id = ? AND q.practice_id = cq.practice_id ' +    
            'WHERE q.practice_id = ?',
            [userId, practiceId]
        );
        
        res.json(questions);
    } catch (error) {
        console.error('获取选择题作答情况时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 获取填空题作答情况
router.get('/api/fill-questions/:practiceId', async (req, res) => {
    const { practiceId } = req.params;
    const { userId } = req.query;
    
    try {
        // 查询填空题信息
        const [questions] = await pool.execute(
            'SELECT q.*, ucq.* ' +
            'FROM fill_questions q ' +
            'LEFT JOIN commited_fill_question ucq ON q.question_order = ucq.question_order AND ucq.commit_user_id = ? ' +
            'WHERE q.practice_id = ?',
            [userId, practiceId]
        );
        
        res.json(questions);
    } catch (error) {
        console.error('获取填空题作答情况时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 获取解答题作答情况
router.get('/api/essay-questions/:practiceId', async (req, res) => {
    const { practiceId } = req.params;
    const { userId } = req.query;
    
    try {
        // 查询解答题信息
        const [questions] = await pool.execute(
            'SELECT q.*, ucq.commited_answer as user_answer, ucq.score as user_score ' +
            'FROM essay_questions q ' +
            'LEFT JOIN commited_essay_question ucq ON q.question_order = ucq.question_order AND ucq.commit_user_id = ? ' +
            'WHERE q.practice_id = ?',
            [userId, practiceId]
        );
        
        res.json(questions);
    } catch (error) {
        console.error('获取解答题作答情况时出错:', error);
        res.status(500).json({ message: '服务器内部错误' });
    }
});

// 更新解答题得分
router.post('/update-essay-score', async (req, res) => {
    const { userId, practiceId, questionOrder, newScore } = req.body;

    try {
        // 1. 检查题目是否存在
        const [essayQuestions] = await pool.execute(
            'SELECT * FROM essay_questions WHERE practice_id = ? AND question_order = ?',
            [practiceId, questionOrder]
        );

        if (essayQuestions.length === 0) {
            return res.status(404).json({ success: false, message: '题目不存在' });
        }

        // 2. 检查用户是否已提交过该题目
        const [commitedQuestions] = await pool.execute(
            'SELECT practice_id FROM commited_essay_question WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
            [practiceId, userId, questionOrder]
        );

        if (commitedQuestions.length === 0) {
            return res.status(404).json({ success: false, message: '用户未提交该解答题，无法更新分数' });
        }

        // 3. 更新解答题得分
        await pool.execute(
            'UPDATE commited_essay_question SET score = ? WHERE practice_id = ? AND commit_user_id = ? AND question_order = ?',
            [newScore, practiceId, userId, questionOrder]
        );

        res.json({ success: true, message: '解答题得分更新成功' });
    } catch (error) {
        console.error('更新解答题得分失败:', error);
        res.status(500).json({ success: false, message: '服务器内部错误' });
    }
});

module.exports = router;